#include "ali_yun.h"
#include "wifi.h"
#include "string.h"
#include "stdio.h"
#include "stdlib.h"

//======================wifi======================
extern uint8_t wifi_RxBuff[256];
extern volatile uint8_t wifi_RxCounter;
// ================================================
//=====================����=======================
double temp_value;
uint8_t humi_value;

//================================================
void ESP8266_Clear(void);
uint8_t Mosquitto_Init(void)
{
    u1_USART("=================网络配置成功============\n");
    // 设置用户名，密码
    if (WIFI_Config(50, "AT+MQTTUSERCFG=0,1,\"NULL\",\"" ALI_USERNAME "\",\"" ALI_PASSWD "\",0,0,\"\"\r\n", "OK"))
    {
        u1_USART("配置用户名及密码失败!\n");
        return 1;
    }
    else
        u1_USART("配置用户名及密码成功!\n");

    // ���ÿͷ� id
    if (WIFI_Config(50, "AT+MQTTCLIENTID=0,\"" ALICLIENTLD "\"\r\n", "OK"))
    {
        u1_USART("2、设置客服ID失败!\n");
        return 1;
    }
    else
        u1_USART("2、设置客服ID成功!!\n");

    u1_USART("\n");
    HAL_Delay(2);

    if (WIFI_Config(50, "AT+MQTTCONN=0,\"" ALI_MQTT_HOSTURL "\"," ALI_PORT ",1\r\n", "OK"))
    {
        u1_USART("3、连接失败!\n");
        return 1;
    }
    else
        u1_USART("3、连接成功\n");

    u1_USART("\n");
    Mosquitto_Topic();
    Mosquitto_Publish(ALI_TOPIC_POST, "hello han ~", 1);
    ESP8266_Clear();
    return 0;
}
void Mosquitto_Topic(void) // 订阅主题
{
    if (WIFI_Config(50, "AT+MQTTSUB=0,\"" ALI_TOPIC_SET "\",1\r\n", "OK"))
    {
        u1_USART("4、订阅消息失败!\n");
    }
    else
        u1_USART("4、订阅消息成功!\n");

    u1_USART("\n");
}

/**
 * 发布MQTT消息
 * @param topic 发布的主题
 * @param message 消息内容
 * @param qos QoS级别(0,1,2)
 * @return 成功返回0，失败返回非0
 */
int Mosquitto_Publish(const char *topic, const char *message, int qos)
{
    char cmd[256] = {0};

    // 构建AT指令：AT+MQTTPUB=0,"topic",qos,0,"message"\r\n
    snprintf(cmd, sizeof(cmd), "AT+MQTTPUB=0,\"%s\",\"%s\",%d,1\r\n", topic, message, qos);
    // AT+MQTTPUB=<LinkID>,<"topic">,<"data">,<qos>,<retain>
    // 发送AT指令并等待响应
    if (WIFI_Config(100, cmd, "OK"))
    {
        u1_USART("发布消息失败!\n");
        return -1;
    }
    else
    {
        u1_USART("发布消息成功!\n");
        return 0;
    }
}

uint8_t cjson_err_num = 0; // cjson
void Mosquitto_GetRCV(void)
{
    cJSON *cjson = NULL;
    int num;
    char topic_buff[256];
    char recv_buffer[1024];
    // printf("======================== WiFi_RX_BUF=: %s\r\n", WiFi_RX_BUF);
    char *ptr_recv = strstr((const char *)WiFi_RX_BUF, "+MQTTSUBRECV");

    if (ptr_recv != NULL) //
    {
        memset(topic_buff, 0, sizeof(topic_buff)); // 清空缓冲区
        sscanf((char *)WiFi_RX_BUF, "+MQTTSUBRECV:0,%[^,],%d,%s", topic_buff, &num, recv_buffer);
        if (strstr(topic_buff, ALI_TOPIC_SET)) // 判断主题
        {
            u1_USART("========================数据解析开始===========================\n");
            u1_USART("接收数据成功，开始解析 %%s\n", recv_buffer);
            cjson = cJSON_Parse(recv_buffer);

            if (cjson == NULL)
            {
                u1_USART("cjson 解析错误\n");
                cjson_err_num++;

                if (cjson_err_num > 3)
                {
                    ESP8266_Clear();
                    cjson_err_num = 0;
                }
                u1_USART("========================数据解析失败=======================\n");
            }
            else
            {
                cJSON *json_data = NULL;
                json_data = cJSON_GetObjectItem(cjson, "params");
                cjson_err_num = 0;

                if (json_data == NULL)
                {
                    u1_USART("cjson 没有数据\n");
                    return;
                }
                else
                {
                    u1_USART("cjson 内存大小为  = %d\n", sizeof(cjson));

                    if (cJSON_GetObjectItem(json_data, "LEDSwitch") != NULL)
                    {
                        humi_value = cJSON_GetObjectItem(json_data, "LEDSwitch")->valuedouble;
                        u1_USART("csjon�����ɹ� Humidity = %d\\n", humi_value);
                        uint8_t msg_buf[1024];
                        HAL_GPIO_WritePin(GPIOC, GPIO_PIN_13, humi_value != 0 ? GPIO_PIN_SET : GPIO_PIN_RESET);
                        sprintf((char *)msg_buf, "AT+MQTTPUB=0,\"" ALI_TOPIC_POST "\",\"{params:{\\\"LEDSwitch\\\":%d}}\",0,0\r\n", humi_value);
                        ESP8266_USART("%s", msg_buf);
                    }

                    //======================================================================================
                }

                ESP8266_Clear();
                cJSON_Delete(cjson);
                printf("========================wancheng===========================\n");
            }
        }
    }
    else
    {
        ESP8266_Clear();
    }
}
void ESP8266_Clear(void) 
{
    memset(WiFi_RX_BUF, 0, sizeof(WiFi_RX_BUF)); 
    wifi_RxCounter = 0;                          
}
